package com.jsyl.application.authority.impl;

import com.jsyl.application.authority.ISensoryIntegrationApplication;


import com.alibaba.fastjson.JSONObject;
import com.jsyl.application.base.impl.BaseApplicationImpl;
import com.jsyl.dao.authority.*;
import com.jsyl.dao.base.BaseDao;
import com.jsyl.entity.authority.*;
import com.jsyl.entity.request.AuditoryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * @author dawm
 */
@Service
@Transactional(value = "defaultTm")
public class SensoryIntegrationApplicationImpl extends BaseApplicationImpl<SensoryIntegration> implements ISensoryIntegrationApplication {

    @Autowired
    private SensoryIntegrationDao sensoryIntegrationDao;

    @Autowired
    private ChildAbilityFeedbackConfigDao childAbilityFeedbackConfigDao;

    @Autowired
    private ScheduleProjectSubjectDao scheduleProjectSubjectDao;

    @Autowired
    private ScheduleChildProjectsDao scheduleChildProjectsDao;

    @Autowired
    private AvailableVisualProjectsDao availableVisualProjectsDao;

    @Override
    public BaseDao<SensoryIntegration> getBaseDao() {
        return this.sensoryIntegrationDao;
    }

    @Override
    @Transactional(value = "defaultTm")
    public JSONObject auditoryMerge(AuditoryRequest request) {
        JSONObject jsonObject = new JSONObject();
        // 1.1把child_ability_feedback_config中的code name为 “dqdj” 修改
        ChildAbilityFeedbackConfig config = childAbilityFeedbackConfigDao.get(request.getAbilityId());
        if (!config.getValue().equals(request.getValue())) {
            config.setValue(request.getValue());
            config.setLast_updated_time(new Date());
            childAbilityFeedbackConfigDao.update(config);
            // 1.2 删除【schedule_project_subject】表中，当前课节当前孩子当前项目【code】对应的全部记录。
            List<ScheduleProjectSubject> scheduleProjectSubject = getscheduleProjectSubjects(request);
            for (ScheduleProjectSubject projects : scheduleProjectSubject) {
                scheduleProjectSubjectDao.delete(projects.getId());
            }
        }
        jsonObject.put("result", true);
        return jsonObject;
    }

    @Override
    @Transactional(value = "defaultTm")
    public JSONObject visualMerge(AuditoryRequest request) {
        JSONObject jsonObject = new JSONObject();
        int Index = 3;
        //获得值集合
        List<String> value = getNameVal(request);
        //获得修改 把child_ability_feedback_config 的三个id dqnlnl、dqnlnj、dqnddj
        List<String> name = getName();
        for (int i = 0; i < name.size(); i++) {
            ChildAbilityFeedbackConfig config = getAbilityId(request.getChildId(), request.getCode(), name.get(i));
            if (!value.get(i).equals(config.getValue())) {
                config.setValue(value.get(i));
                config.setLast_updated_time(new Date());
                childAbilityFeedbackConfigDao.update(config);
            } else {
                Index = Index - 1;
            }
        }
        //有修改则要删除 schedule_project_subject
        if (Index != 0) {
            List<ScheduleProjectSubject> scheduleChildProjectses = getscheduleProjectSubjects(request);
            for (ScheduleProjectSubject projects : scheduleChildProjectses) {
                scheduleProjectSubjectDao.delete(projects.getId());
            }
        }

        jsonObject.put("result", true);
        return jsonObject;
    }

    //视觉能力剔除
    @Override
    @Transactional(value = "defaultTm")
    public JSONObject visualAdd(AuditoryRequest request) {
        JSONObject jsonObject = new JSONObject();
        Date date = new Date();
        // 1.删除child_ability_feedback_config 表中的数据
        List<ChildAbilityFeedbackConfig> configs = getChildAbilityFeedbackConfig(request);
        for (ChildAbilityFeedbackConfig config : configs) {
            childAbilityFeedbackConfigDao.delete(config.getId());
        }
        // 2.删除 available_visual_projects中的code记录
        List<AvailableVisualProjects> availableVisual = getAvailableVisualProjects(request);
        for (AvailableVisualProjects projects : availableVisual) {
            availableVisualProjectsDao.delete(projects.getId());
        }
        // 3.增加获得有参数的name
        Map<String, String> visualNameVal = getAddVisualName(request);
        Iterator iter = visualNameVal.entrySet().iterator();
        //将需选择当前能力年龄、当前能力年级、当前难度等级，把所选择的视觉项目添加到【child_ability_feedback_config】表中
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            ChildAbilityFeedbackConfig config = new ChildAbilityFeedbackConfig();
            config.setCode(request.getCode());
            config.setChildId(request.getChildId());
            config.setCreate_time(date);
            config.setLast_updated_time(date);
            config.setName((String) entry.getKey());
            config.setValue((String) entry.getValue());
            childAbilityFeedbackConfigDao.insert(config);
        }

        // 2.根据所选择项目的优先级，添加记录到【available_visual_projects】表中
        // 2.1判断有没有存在,存在不做操作,不存在增加
        if (null == getAvailableVisualProject(request,request.getCode())) {
            // 2.2获得孩子最大编号
            Integer cycleId = availableVisualProjectsDao.getMaxCycleId(request.getChildId());
            //2.3获得孩子训练次数
            List<Integer> times = getTrainingTimes(request);
            Integer trainingTimes = null;
            Integer trainedTimes = null;
            Integer priority = getProjectsTrainingTimes(request);
            // 如果si表存在孩子与code
            if (null!=times && times.size()==2) {
                trainingTimes = times.get(0);
                trainedTimes = times.get(1);
                if (trainingTimes-trainedTimes==5){
                    priority = 0;
                }
            } else {
                // 获取si表的 // TODO: 16/12/13 总次数 获得有点问题
                trainingTimes = 5-priority;
                trainedTimes = 0;
            }
            AvailableVisualProjects visualProjects = new AvailableVisualProjects();
            if (judgeCode(request.getCode())) {
                visualProjects.setTrainedTimes(5);
                visualProjects.setTrainingTimes(0);
                visualProjects.setPriority(0);
            } else {
                visualProjects.setTrainedTimes(trainingTimes);
                visualProjects.setTrainingTimes(trainedTimes);
                visualProjects.setPriority(priority);
            }
            visualProjects.setChildId(request.getChildId());
            visualProjects.setProjectCode(request.getCode());
            visualProjects.setCreateTime(date);
            visualProjects.setIsFinished(0);
            visualProjects.setCycleId(cycleId);
            availableVisualProjectsDao.insert(visualProjects);
        }
        // 3.2.5 在【schedule_child_projects】表中替换当节课该孩子的项目，将新增的项目替换删除的项目
        ScheduleChildProjects projects = getscheduleChildProjects(request);
        String oldProjects = projects.getProjects();
        String newProjects = "";
        String[] projectCode = oldProjects.split(",");
        for (String code : projectCode) {
            if (request.getOldCode().equals(code)) {
                newProjects += request.getCode() + ",";
            } else {
                newProjects += code + ",";
            }
        }
        if (newProjects.length() > 1) {
            newProjects = newProjects.substring(0, newProjects.length() - 1);
        }
        projects.setProjects(newProjects);
        scheduleChildProjectsDao.update(projects);
        // 3.2.6 删除【schedule_project_subject】表中，当节课该孩子这个code的记录
        ScheduleProjectSubject Project = getscheduleProjectSubject(request);
        Project.setProjectCode(request.getCode());
        scheduleProjectSubjectDao.update(Project);

        jsonObject.put("result", true);
        return jsonObject;
    }

    @Override
    @Transactional(value = "defaultTm")
    public JSONObject visualReplace(AuditoryRequest request) {
        Date date = new Date();
        JSONObject jsonObject = new JSONObject();
        // 1.替换 available_visual_projects
        AvailableVisualProjects availableVisualProject =  availableVisualProjectsDao.getMaxCycle(request.getChildId(),request.getOldCode());
        availableVisualProject.setProjectCode(request.getCode());
        availableVisualProjectsDao.update(availableVisualProject);
        // 2.child_ability_feedback_config
        Map<String, String> visualNameVal = getAddVisualName(request);
        Iterator iter = visualNameVal.entrySet().iterator();
        //将需选择当前能力年龄、当前能力年级、当前难度等级，把所选择的视觉项目添加到【child_ability_feedback_config】表中
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            ChildAbilityFeedbackConfig config = getAbilityId(request.getChildId(), request.getCode(), (String) entry.getKey());
            if(null!=config){
                config.setCode(request.getCode());
                config.setChildId(request.getChildId());
                config.setCreate_time(date);
                config.setLast_updated_time(date);
                config.setName((String) entry.getKey());
                config.setValue((String) entry.getValue());
                childAbilityFeedbackConfigDao.update(config);
            }else {
                ChildAbilityFeedbackConfig newConfig = new ChildAbilityFeedbackConfig();
                newConfig.setCode(request.getCode());
                newConfig.setChildId(request.getChildId());
                newConfig.setCreate_time(date);
                newConfig.setLast_updated_time(date);
                newConfig.setName((String) entry.getKey());
                newConfig.setValue((String) entry.getValue());
                childAbilityFeedbackConfigDao.insert(newConfig);
            }
        }
        // 3.2.5 在【schedule_child_projects】表中替换当节课该孩子的项目，将新增的项目替换删除的项目
        ScheduleChildProjects projects = getscheduleChildProjects(request);
        String oldProjects = projects.getProjects();
        String newProjects = "";
        String[] projectCode = oldProjects.split(",");
        for (String code : projectCode) {
            if (request.getOldCode().equals(code)) {
                newProjects += request.getCode() + ",";
            } else {
                newProjects += code + ",";
            }
        }
        if (newProjects.length() > 1) {
            newProjects = newProjects.substring(0, newProjects.length() - 1);
        }
        projects.setProjects(newProjects);
        scheduleChildProjectsDao.update(projects);
        // 3.2.6 删除【schedule_project_subject】表中，当节课该孩子这个code的记录
        ScheduleProjectSubject Project = getscheduleProjectSubject(request);
        Project.setProjectCode(request.getCode());
        scheduleProjectSubjectDao.update(Project);

        jsonObject.put("result", true);
        return jsonObject;
    }

    //  判断 0113开头 5000
    private Boolean judgeCode(String code) {
        if (code.length() > 4) {
            if ("0113".equals(code.substring(0, 4))) {
                return true;
            }
        }
        return false;
    }

    //视觉增加 获得有增加的名字和值
    private Map<String, String> getAddVisualName(AuditoryRequest request) {
        Map<String, String> visualName = new HashMap<String, String>();
        visualName.put("vqt", "1");
        visualName.put("ljtgcs", "0");
        if (null != request.getDqnddj() && !request.getDqnddj().equals("")) {
            visualName.put("dqnddj", request.getDqnddj());
        }
        if (null != request.getDqnlnj() && !request.getDqnlnj().equals("")) {
            visualName.put("dqnlnj", request.getDqnlnj());
        }
        if (null != request.getDqnlnl() && !request.getDqnlnl().equals("")) {
            visualName.put("dqnlnl", request.getDqnlnl());
        }
        return visualName;
    }

    //获得所有的视觉项目
    @Override
    public List<SensoryIntegration> findVisual(String childId) {
        return sensoryIntegrationDao.findVisual(childId);
    }

    //获得次数
    private Integer getProjectsTrainingTimes(AuditoryRequest request) {
        //取到原来availableVisualProjects表的数据
        Map<String, Object> configParam = new HashMap<String, Object>();
        configParam.put("code", request.getCode());
        SensoryIntegration configs = sensoryIntegrationDao.getByFields(configParam);
        return configs.getPriority();
    }


    //获得次数
    private List<Integer> getTrainingTimes(AuditoryRequest request) {
        //取到原来availableVisualProjects表的数据
        AvailableVisualProjects configs = getAvailableVisualProject(request,request.getCode());
        List<Integer> times = new ArrayList<Integer>();
        if (null != configs) {
            times.add(configs.getTrainingTimes());
            times.add(configs.getTrainedTimes() + 1);
            times.add(configs.getPriority());
            return times;
        }
        return null;
    }

    //获得名字
    private List<String> getNameVal(AuditoryRequest request) {
        List<String> getNameVal = new ArrayList<String>();
        getNameVal.add(request.getDqnlnl());
        getNameVal.add(request.getDqnlnj());
        getNameVal.add(request.getDqnddj());
        return getNameVal;
    }

    private List<String> getName() {
        List<String> name = new ArrayList<String>();
        name.add("dqnlnl");
        name.add("dqnlnj");
        name.add("dqnddj");
        return name;
    }

    private ChildAbilityFeedbackConfig getAbilityId(Integer childId, String Code, String name) {
        Map<String, Object> configParam = new HashMap<String, Object>();
        configParam.put("childId", childId);
        configParam.put("code", Code);
        configParam.put("name", name);
        ChildAbilityFeedbackConfig config = childAbilityFeedbackConfigDao.getByFields(configParam);
        return config;
    }

    private ScheduleProjectSubject getscheduleProjectSubject(AuditoryRequest request) {
        Map<String, Object> configParam = new HashMap<String, Object>();
        configParam.put("childId", request.getChildId());
        configParam.put("projectCode", request.getOldCode());
        configParam.put("scheduleId", request.getScheduleId());
        return scheduleProjectSubjectDao.getByFields(configParam);
    }

    private List<ScheduleProjectSubject> getscheduleProjectSubjects(AuditoryRequest request) {
        Map<String, Object> configParam = new HashMap<String, Object>();
        configParam.put("childId", request.getChildId());
        configParam.put("projectCode", request.getCode());
        configParam.put("scheduleId", request.getScheduleId());
        return scheduleProjectSubjectDao.findByFields(configParam);
    }

    private ScheduleChildProjects getscheduleChildProjects(AuditoryRequest request) {
        Map<String, Object> configParam = new HashMap<String, Object>();
        configParam.put("childId", request.getChildId());
        configParam.put("scheduleId", request.getScheduleId());
        return scheduleChildProjectsDao.getByFields(configParam);
    }

    private List<ChildAbilityFeedbackConfig> getChildAbilityFeedbackConfig(AuditoryRequest request) {
        Map<String, Object> configParam = new HashMap<>();
        configParam.put("childId", request.getChildId());
        configParam.put("code", request.getOldCode());
        return childAbilityFeedbackConfigDao.findByFields(configParam);
    }

    private List<AvailableVisualProjects> getAvailableVisualProjects(AuditoryRequest request) {
        Map<String, Object> configParam = new HashMap<>();
        configParam.put("childId", request.getChildId());
        configParam.put("projectCode", request.getOldCode());
        return availableVisualProjectsDao.findByFields(configParam);
    }

    private AvailableVisualProjects getAvailableVisualProject(AuditoryRequest request,String code) {
        Map<String, Object> configParam = new HashMap<>();
        configParam.put("childId", request.getChildId());
        configParam.put("projectCode", code);
        return availableVisualProjectsDao.getByFields(configParam);
    }


}
